﻿using INTEX.DataBase;
using INTEX.DataBase.Tools;
using ReflectionStudio.Components.UserControls;
using ReflectionStudio.Core.Events;
using ReflectionStudio.Core.Helpers;
using System;
using System.Data;
using System.Linq;
using System.Windows;
using System.Windows.Data;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Threading;
namespace WPFExcelReport
{
    /// <summary>
    /// Interaction logic for ProductionOrder.xaml
    /// </summary>
    public partial class YGRABDOC
    {
        #region ==TXTISIND===========
        public static readonly DependencyProperty TXTISINDProperty = DependencyProperty.Register("TXTISIND",
            typeof(string), typeof(YGRABDOC),
            new FrameworkPropertyMetadata("", FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, OnTXTISINDChanged));
        public string TXTISIND
        {
            get
            {
                return (string)GetValue(TXTISINDProperty);
            }
            set
            {
                SetValue(TXTISINDProperty, value);
            }
        }
        private static void OnTXTISINDChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
        {
            var source = sender as YGRABDOC;
            if (source != null)
            {
                source.TXTISIND = (string)e.NewValue;
            }
        }
        #endregion

        #region ==IsCanChgGAAUF===========
        public static readonly DependencyProperty IsCanChgGAAUFProperty = DependencyProperty.Register("IsCanChgGAAUF",
            typeof(bool), typeof(YGRABDOC),
            new FrameworkPropertyMetadata(true, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, OnIsCanChgGAAUFChanged));
        public bool IsCanChgGAAUF
        {
            get
            {
                return (bool)GetValue(IsCanChgGAAUFProperty);
            }
            set
            {
                SetValue(IsCanChgGAAUFProperty, value);
            }
        }
        private static void OnIsCanChgGAAUFChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
        {
            var source = sender as YGRABDOC;
            if (source != null)
            {
                source.IsCanChgGAAUF = (bool)e.NewValue;
            }
        }
        #endregion

        #region ==IsCanPrint===========
        public static readonly DependencyProperty IsCanPrintProperty = DependencyProperty.Register("IsCanPrint",
            typeof(bool), typeof(YGRABDOC),
            new FrameworkPropertyMetadata(true, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, OnIsCanPrintChanged));
        public bool IsCanPrint
        {
            get
            {
                return (bool)GetValue(IsCanPrintProperty);
            }
            set
            {
                SetValue(IsCanPrintProperty, value);
            }
        }
        private static void OnIsCanPrintChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
        {
            var source = sender as YGRABDOC;
            if (source != null)
            {
                source.IsCanPrint = (bool)e.NewValue;
            }
        }
        #endregion

        #region ==IsGridEdit===========
        public static readonly DependencyProperty IsGridEditProperty = DependencyProperty.Register("IsGridEdit",
            typeof(bool), typeof(YGRABDOC),
            new FrameworkPropertyMetadata(false, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, OnIsGridEditChanged));
        public bool IsGridEdit
        {
            get
            {
                return (bool)GetValue(IsGridEditProperty);
            }
            set
            {
                SetValue(IsGridEditProperty, value);
            }
        }
        private static void OnIsGridEditChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
        {
            var source = sender as YGRABDOC;
            if (source != null)
            {
                source.IsGridEdit = (bool)e.NewValue;
            }
        }
        #endregion


        #region-------------Properties-----------------------

        YGRABDOCData m_Data;
        ITXEXRPT ITXEXRPT;
        public ApplicationBase app
        {
            get
            {
                return ApplicationBase.Instance;
            }
        }
        INTEXDBC INTEXDBC
        {
            get
            {
                return app.INTEXDBC;
            }
        }
        public INTEXBL INTEXBL
        {
            get
            {
                return app.INTEXBL;
            }
        }
        public SETINTEXDB SetData
        {
            get
            {
                return (SETINTEXDB)TryFindResource("SetData");
            }
        }
        public SETINTEXDB SetDetail
        {
            get
            {
                return (SETINTEXDB)TryFindResource("SetDetail");
            }
        }
        public SETINTEXDB SetEnv
        {
            get
            {
                return (SETINTEXDB)TryFindResource("SetEnv");
            }
        }
        public SETINTEXDB SetStock
        {
            get
            {
                return (SETINTEXDB)TryFindResource("SetStock");
            }
        }

        #region=====vwABPOS=======
        CollectionViewSource vwABPOS
        {
            get
            {
                return (CollectionViewSource)this.TryFindResource("vwABPOS");
            }
        }
        DataRow dwABPOS
        {
            get
            {
                if (vwABPOS.View == null)
                    return null;
                if ((DataRowView)vwABPOS.View.CurrentItem == null)
                    return null;
                return ((DataRowView)vwABPOS.View.CurrentItem).Row;
            }
        }
        #endregion
        #region=====vwXABPOS=======
        CollectionViewSource vwXABPOS
        {
            get
            {
                return (CollectionViewSource)this.TryFindResource("vwXABPOS");
            }
        }
        DataRow dwXABPOS
        {
            get
            {
                if (vwXABPOS.View == null)
                    return null;
                if ((DataRowView)vwXABPOS.View.CurrentItem == null)
                    return null;
                return ((DataRowView)vwXABPOS.View.CurrentItem).Row;
            }
        }
        #endregion
        #region=====vwTABPOS=======
        CollectionViewSource vwTABPOS
        {
            get
            {
                return (CollectionViewSource)this.TryFindResource("vwTABPOS");
            }
        }
        DataRow dwTABPOS
        {
            get
            {
                if (vwTABPOS.View == null)
                    return null;
                if ((DataRowView)vwTABPOS.View.CurrentItem == null)
                    return null;
                return ((DataRowView)vwTABPOS.View.CurrentItem).Row;
            }
        }
        #endregion
        #region=====vwYARNA=======
        CollectionViewSource vwYARNA
        {
            get
            {
                return (CollectionViewSource)this.TryFindResource("vwYARNA");
            }
        }
        DataRow dwYARNA
        {
            get
            {
                if (vwYARNA.View == null)
                    return null;
                if ((DataRowView)vwYARNA.View.CurrentItem == null)
                    return null;
                return ((DataRowView)vwYARNA.View.CurrentItem).Row;
            }
        }

        #endregion
        #region=====vwGAAUF=======
        CollectionViewSource vwGAAUF
        {
            get
            {
                return (CollectionViewSource)this.TryFindResource("vwGAAUF");
            }
        }
        DataRow dwGAAUF
        {
            get
            {
                if (vwGAAUF.View == null)
                    return null;
                if ((DataRowView)vwGAAUF.View.CurrentItem == null)
                    return null;
                return ((DataRowView)vwGAAUF.View.CurrentItem).Row;
            }
        }
        #endregion
        #region=====vwMU=======
        CollectionViewSource vwMU
        {
            get
            {
                return (CollectionViewSource)this.TryFindResource("vwMU");
            }
        }
        DataRow dwMU
        {
            get
            {
                if (vwMU.View == null)
                    return null;
                if ((DataRowView)vwMU.View.CurrentItem == null)
                    return null;
                return ((DataRowView)vwMU.View.CurrentItem).Row;
            }
        }
        #endregion
        #region=====  vwYGAAUF=======
        CollectionViewSource vwYGAAUF
        {
            get
            {
                return (CollectionViewSource)this.TryFindResource("vwYGAAUF");
            }
        }
        DataRow dwYGAAUF
        {
            get
            {
                if (vwYGAAUF.View == null)
                    return null;
                if ((DataRowView)vwYGAAUF.View.CurrentItem == null)
                    return null;
                return ((DataRowView)vwYGAAUF.View.CurrentItem).Row;
            }
        }
        #endregion
        #region=====  vwGLLG=======
        CollectionViewSource vwGLLG
        {
            get
            {
                return (CollectionViewSource)this.TryFindResource("vwGLLG");
            }
        }
        DataRow dwGLLG
        {
            get
            {
                if (vwGLLG.View == null)
                    return null;
                if ((DataRowView)vwGLLG.View.CurrentItem == null)
                    return null;
                return ((DataRowView)vwGLLG.View.CurrentItem).Row;
            }
        }
        #endregion

        public string KRS
        {
            get
            {
                return m_Data.Right("  " + txtAUFKRS.Text.ToString().Trim(), 2);
            }
            set
            {
                txtAUFKRS.Text = value;
            }
        }
        public string LFD
        {
            get
            {
                return m_Data.Right("000000" + txtAUFLFD.Text.ToString().Trim(), 6); ;
            }
            set
            {
                txtAUFLFD.Text = value;
            }
        }
        string POS
        {
            get
            {
                return m_Data.Right("000" + txtAUFPOS.Text.ToString().Trim(), 3); ;
            }
            set
            {
                txtAUFPOS.Text = value;
            }
        }
        decimal BatchQty
        {
            get
            {
                if (txtBatchQty.Text.Trim() == "")
                    txtBatchQty.Text = "0";
                return Convert.ToDecimal(txtBatchQty.Text.ToString());
            }
            set
            {
                txtBatchQty.Text = value.ToString();
            }
        }
        decimal Batches
        {
            get
            {
                if (txtBatches.Text.Trim() == "")
                    txtBatches.Text = "0";
                return Convert.ToDecimal(txtBatches.Text.ToString());
            }
            set
            {
                txtBatches.Text = value.ToString();
            }
        }

        double ABPQTY
        {
            get
            {
                if (dwABPOS == null)
                    return 0;
                return Convert.ToDouble(dwABPOS["ABPSOLLMENGE5"].ToString()) / 100;
            }
        }
        double VKPQTY
        {
            get
            {
                if (dwABPOS == null)
                    return 0;
                return Convert.ToDouble(dwABPOS["ABPSOLLMENGE7"].ToString()) / 100;
            }
        }
        BindingListCollectionView cvMGAAUF
        {
            get
            {
                return (BindingListCollectionView)CollectionViewSource.GetDefaultView(this.dlgMGAAUF.ItemsSource);
            }
        }
        BindingListCollectionView cvGAAUF
        {
            get
            {
                return (BindingListCollectionView)CollectionViewSource.GetDefaultView(this.dlgABP.ItemsSource);
            }
        }
        BindingListCollectionView cvYARNA
        {
            get
            {
                return (BindingListCollectionView)CollectionViewSource.GetDefaultView(this.dlgYARNA.ItemsSource);
            }
        }
        BindingListCollectionView cvMaster
        {
            get
            {
                return (BindingListCollectionView)CollectionViewSource.GetDefaultView(this.dlgMaster.ItemsSource);
            }
        }
        bool IsRepair = false;
        #region ==IsCalculate===========
        public static readonly DependencyProperty IsCalculateProperty = DependencyProperty.Register("IsCalculate",
            typeof(bool), typeof(YGRABDOC),
            new FrameworkPropertyMetadata(false, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, OnIsCalculateChanged));
        public bool IsCalculate
        {
            get
            {
                return (bool)GetValue(IsCalculateProperty);
            }
            set
            {
                SetValue(IsCalculateProperty, value);
            }
        }
        private static void OnIsCalculateChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
        {
            var src = sender as YGRABDOC;
            if (src != null)
            {
                src.IsCalculate = (bool)e.NewValue;
            }
        }
        #endregion
        #region ==IsSave===========
        public static readonly DependencyProperty IsSaveProperty = DependencyProperty.Register("IsSave",
            typeof(bool), typeof(YGRABDOC),
            new FrameworkPropertyMetadata(false, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, OnIsSaveChanged));
        public bool IsSave
        {
            get
            {
                return (bool)GetValue(IsSaveProperty);
            }
            set
            {
                SetValue(IsSaveProperty, value);
            }
        }
        private static void OnIsSaveChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
        {
            var src = sender as YGRABDOC;
            if (src != null)
            {
                src.IsSave = (bool)e.NewValue;
            }
        }
        #endregion
        #region ==IsRatio===========
        public static readonly DependencyProperty IsRatioProperty = DependencyProperty.Register("IsRatio",
            typeof(bool), typeof(YGRABDOC),
            new FrameworkPropertyMetadata(false, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, OnIsRatioChanged));
        public bool IsRatio
        {
            get
            {
                return (bool)GetValue(IsRatioProperty);
            }
            set
            {
                SetValue(IsRatioProperty, value);
            }
        }
        private static void OnIsRatioChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
        {
            var src = sender as YGRABDOC;
            if (src != null)
            {
                src.IsRatio = (bool)e.NewValue;
            }
        }
        #endregion



        #endregion
        #region ==dwAB===========
        public static readonly DependencyProperty dwABProperty = DependencyProperty.Register("dwAB",
        typeof(DataRow), typeof(YGRABDOC),
        new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, OdwABChanged));

        public DataRow dwAB
        {
            get
            {
                return (DataRow)GetValue(dwABProperty);
            }
            set
            {
                SetValue(dwABProperty, value);
            }
        }
        private static void OdwABChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
        {
            var src = sender as YGRABDOC;
            if (src != null)
            {
                DataRow row = (DataRow)e.NewValue;
                src.dwAB = row;
            }
        }
        #endregion
        bool IsINBookingmode = false;
        public override void OnWorkflowIDChange(MessageEventArgs e)
        {
            base.OnWorkflowIDChange(e);
            string wid = e.Info.Details;
            string order = "";
            switch (wid)
            {
                case "YGRABDOC":
                    order = e.Info.ORDER.PadRight(12);
                    txtAUFKRS.Text = order.Substring(0, 2);
                    txtAUFLFD.Text = order.Substring(2, 6);
                    break;
            }
        }
        public YGRABDOC()
        {
            try
            {
                InitializeComponent();
                DataTable tb = SetDetail.ZUTEI.Clone();
                tb.TableName = "ZUTEI_EXT";
                SetDetail.Merge(tb);
                this.Name = "纺纱生产";
                m_Data = new YGRABDOCData();
                ITXEXRPT = new ITXEXRPT();
                ITXEXRPT.Root = "C:\\IntexReport";
                ITXEXRPT.strCompany = app.company;
                ITXEXRPT.PrintType = "OpenExcel";
                ResetTab();
                //IsRatio =true;
                IsINBookingmode = false;
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }
        public void ResetTab()
        {
            IsCalculate = false;
            IsSave = false;
        }
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                if (IsLoaded)
                    return;
                IsLoaded = true;
                IsRatio = false;
                SetEnv.Clear();
                SetEnv.Merge(m_Data.LoadEnv());
                vwABPOS.View.CurrentChanged += vwABPOS_CurrentChanged;
                vwMU.View.CurrentChanged += vwMU_CurrentChanged;
                vwYGAAUF.View.CurrentChanged += vwYGAAUF_CurrentChanged;
                vwGAAUF.View.CurrentChanged += vwGAAUF_CurrentChanged;
                vwYARNA.View.CurrentChanged += vwYARNA_CurrentChanged;
                vwGLLG.View.CurrentChanged += vwGLLG_CurrentChanged;
                vwTABPOS.View.CurrentChanged += vwTABPOS_CurrentChanged;
                EventDispatcher.Instance.OnStatusChange += Instance_OnStatusChange;
                txtMessage.Visibility = Visibility.Collapsed;
                BatchQty = Convert.ToDecimal(0);
                cvMaster.CustomFilter = "ABPPOSTYP='HM' OR ABPPOSTYP='HX ' ";

                if (app.User.Trim() == "ITXV")
                {
                    KRS = "B6";
                    LFD = "060092";
                    txtSplitQty.Text = "200";
                    txtFlagSplit.Text = "Y";
                    txtFlagABPART.Text = "Y";
                    txtPOS1.Text = "011";
                    //  btnQuery_Click(null, null);
                    //btnGotoCombine_Click(null, null);
                    //btnCombine_Click(null, null);
                }
                if (!SetEnv.Tables.Contains("SDDAT"))
                {
                    SetEnv.Merge(m_Data.LoadEnv());
                }
                if (SetEnv.Tables["SDDAT"].Rows.Count == 0)
                {
                    SetEnv.Merge(m_Data.LoadEnv());
                }
                if (SetEnv.Tables["SDDAT"].Rows.Count == 0)
                {
                    MessageBox.Show("程序装载有问题，请重新打开");
                }
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }

        void vwTABPOS_CurrentChanged(object sender, EventArgs e)
        {
            dwAB = dwTABPOS;
        }

        void Instance_OnStatusChange(object sender, StatusEventArgs e)
        {
            MessageInfo msg = ((StatusEventArgs)e).Info;
            string Message = msg.Details.Trim();
            if (Message != "")
            {
                txtMessage.Text = msg.Details;
                if (Message.Contains("分盘完成"))
                {
                    txtMessage.Visibility = Visibility.Collapsed;
                    btnQuery_Click(null, null);
                }
                if (Message.Contains("分盘异常终止"))
                {
                    txtMessage.Visibility = Visibility.Collapsed;
                }

            }
        }
        private void btnQuery_Click(object sender, EventArgs e)
        {
            this.Dispatcher.BeginInvoke(DispatcherPriority.Background, new LOADBYAUFDelegate(GetData));

        }
        public void GetData()
        {
            try
            {
                txtMessage.Visibility = Visibility.Collapsed;
                SetDetail.Clear();
                DataSet Result = new DataSet();
                using (new LongOperation(this, "正在收集所有数据"))
                {
                    Result = m_Data.BuildData("00", KRS, LFD);
                }

                SetData.Clear();
                SetData.Merge(Result);
                if (vwABPOS != null)
                {
                    if (vwABPOS.View != null)
                    {
                        vwABPOS.View.MoveCurrentTo(-1);
                    }
                }
                if (vwABPOS.View != null)
                {
                    vwABPOS.View.MoveCurrentToFirst();
                }

                cvGAAUF.CustomFilter = "GASA='713'";
                ResetTab();
                IsINBookingmode = false;
                //IsRatio = true;
            }
            catch (Exception ex)
            {
                SetData.Clear();
                MessageBox.Show("查询遇到了未知错误，通常这个不会看到，请重新启动程序");
                Tracer.Error(ex.StackTrace, ex);
            }
        }

        void vwABPOS_CurrentChanged(object sender, EventArgs e)
        {
            if (dwABPOS == null)
                return;
            DataTable tb = null;
            if (dwABPOS["ABPERLKZ"].ToString() == "J")
            {
                MessageBox.Show("生产单已关闭");

            }

            try
            {
                SetDetail.Merge(SetData);
                SetDetail.Clear();
                SetDetail.Merge(SetData.Tables["ABKOPF"]);
                SetDetail.Merge(SetData.Tables["GSDAT"]);
                SetDetail.Merge(SetData.Tables["GSCOLOR"]);
                SetDetail.Merge(SetData.Tables["GSMATK"]);
                SetDetail.Merge(SetData.Tables["TBABA"]);
                // SetDetail.Merge(SetData.Tables["ABAUFM"]);
                DataRow[] rows = SetData.ABPOS.Select("ABPAUFKRS='" + KRS + "' AND ABPAUFLFD='" + LFD + "' AND ABPAUFPOS='" + POS + "'");
                TXTISIND = "";
                TXTISIND = (KRS + LFD + POS).PadRight(60);
                tb = rows.CopyToDataTable();
                tb.TableName = "ABPOS";
                SetDetail.Merge(tb);
                if (vwTABPOS.View != null)
                {
                    vwTABPOS.View.MoveCurrentToFirst();
                }
                double ABPSOLLMENGE5 = Convert.ToDouble(dwTABPOS["ABPSOLLMENGE5"].ToString());//120
                double ABPSOLLMENGE7 = Convert.ToDouble(dwTABPOS["ABPSOLLMENGE7"].ToString());//100
                double ABPSTKLG = Convert.ToDouble(dwTABPOS["ABPSTKLG"].ToString()) / 10000000;
                if (SetData.Tables.Contains("VKPOS"))
                {
                    SetDetail.Merge(SetData.Tables["VKPOS"]);
                }
                double vkpqty = 0;
                var ABPM = (from DataRow ABP in SetData.Tables["ABPOS"].Rows
                            where ABP["ABPAUFPOS"].ToString() == "020"
                            select ABP["ABPSOLLMENGE7"].ToString()).Max();
                double ABPM7 = Convert.ToDouble((string)ABPM);
                foreach (DataRow row in SetData.Tables["ABAUFM"].Rows)
                {
                    if (row["ABAVKAUFTYP"].ToString() != "K")
                        continue;
                    if (row["ABARESPROG"].ToString().Trim() == "BD")
                        continue;
                    string ABAVKAUFKRS = row["ABAVKAUFKRS"].ToString();
                    string ABAVKAUFLFD = row["ABAVKAUFLFD"].ToString();
                    string ABAVKAUFPOS = row["ABAVKAUFPOS"].ToString();
                    var qVK = (from DataRow VKP in SetData.Tables["VKPOS"].Rows
                               where VKP["VKPAUFKRS"].ToString() == ABAVKAUFKRS
                               && VKP["VKPAUFLFD"].ToString() == ABAVKAUFLFD
                               && VKP["VKPAUFPOS"].ToString() == ABAVKAUFPOS
                               && VKP["VKPSA"].ToString() == "  "
                               select VKP["VKPMENGE1"].ToString()).Max();
                    double VKPMENGE1 = Convert.ToDouble((string)qVK);
                    vkpqty += VKPMENGE1 / 100;
                    if (Math.Abs(VKPMENGE1 - ABPM7) > 100)
                    {

                        // MessageBox.Show("销售订单量有变更，请审核！！！");
                    }

                }
                cVKPQty.Text = vkpqty.ToString();
                //1.初始化TargetRatio,ABPSOLLMENGE5*ABPSTKLG/ABPSOLLMENGE7
                if (dwTABPOS["ABPSTKLG"].ToString() == "0")
                {
                    dwTABPOS["ABPSTKLG"] = 10000000;
                    TargetRatio = 1;
                }
                else
                {

                    //txtAddRatio.Text = (Math.Round(100 * ABPSOLLMENGE5 * ABPSTKLG / ABPSOLLMENGE7) / 100).ToString();
                    txtAddRatio.Text = (Helpers.Helper.RoundX(ABPSOLLMENGE5 * ABPSTKLG / ABPSOLLMENGE7, 1000)).ToString();

                }

                rows = SetData.ABFOLGE.Select("ABFAUFKRS='" + KRS + "' AND ABFAUFLFD='" + LFD + "' AND ABFAUFPOS='" + POS + "'");
                if (rows.Length > 0)
                {
                    tb = rows.CopyToDataTable();
                    tb.TableName = "ABFOLGE";
                    SetDetail.Merge(tb);
                }

                rows = SetData.GAAUF.Select("GAAUFKRS='" + KRS + "' AND GAAUFLFD='" + LFD + "' AND GAAUFPOS='" + POS + "'");
                if (rows.Length > 0)
                {
                    tb = rows.CopyToDataTable();
                    tb.TableName = "GAAUF";
                    SetDetail.Merge(tb);
                    RefreshRatio();
                }
                rows = SetData.Tables["ZUTEI"].Select("ZUAUFKRS='" + KRS + "' AND ZUAUFLFD='" + LFD + "' AND ZUAUFPOS='" + POS + "'");
                if (rows.Length > 0)
                {
                    tb = rows.CopyToDataTable();
                    tb.TableName = "ZUTEI";
                    SetDetail.Merge(tb);
                    dlgZUTEI.Visibility = Visibility.Visible;
                    dlgZUTEIEXT.Visibility = Visibility.Collapsed;
                }
                rows = SetData.Tables["ZUTEI_ITX"].Select("ZUAUFKRS='" + KRS + "' AND ZUAUFLFD='" + LFD + "' AND ZUAUFPOS='" + POS + "'");
                if (rows.Length > 0)
                {
                    tb = rows.CopyToDataTable();
                    tb.TableName = "ZUTEI_ITX";
                    SetDetail.Merge(tb);
                }

                rows = SetData.Tables["ZUTEI_EXT"].Select("ABAVKAUFKRS='" + KRS + "' AND ABAVKAUFLFD='" + LFD + "' AND ABAVKAUFPOS='" + POS + "'");
                if (rows.Length > 0)
                {
                    tb = rows.CopyToDataTable();
                    tb.TableName = "ZUTEI_EXT";
                    SetDetail.Merge(tb);
                    dlgZUTEI.Visibility = Visibility.Collapsed;
                    dlgZUTEIEXT.Visibility = Visibility.Visible;
                }
                btnInitializedMU.IsEnabled = true;
                btnRemoveBatch.IsEnabled = false;
                btnAddBatch.IsEnabled = false;
                rows = SetData.Tables["ABAUFM"].Select(" (ABAAUFKRS='FP' OR  ABAAUFKRS='HX' ) AND ABAVKAUFKRS='" + KRS + "' AND ABAVKAUFLFD='" + LFD + "' AND ABAVKAUFPOS='" + POS + "'");

                if (rows.Length > 0)
                {
                    IsCanChgGAAUF = false;
                    tb = rows.CopyToDataTable();

                    btnInitializedMU.IsEnabled = false;
                    btnRemoveBatch.IsEnabled = true;
                    btnAddBatch.IsEnabled = true;
                    tb.TableName = "ABAUFM";
                    SetDetail.Merge(tb);
                    tb.TableName = "ICC_ABAX";
                    SetDetail.Merge(tb);
                }
                else
                {
                    IsCanChgGAAUF = true;
                }
                DataRow[] rowshx = SetData.GAAUF.Select("GAAUFKRS='" + KRS + "' AND GAAUFLFD='" + LFD + "' AND GAAUFPOS='" + POS + "' AND GAKG2=0");
                if (rowshx.Length > 0)
                {
                    btnInitializedMU.IsEnabled = true;
                }
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
                if (tb.TableName == "ICC_ABAX")
                {
                    SetDetail.Tables["ICC_ABAX"].Clear();
                    tb.TableName = "ICC_ABAX";
                    SetDetail.Merge(tb);
                }
            }
            finally
            {

            }
        }

        private void btnPrintGB12_Click(object sender, EventArgs e)
        {
            try
            {
                ITXEXRPT.dsSource = SetDetail;
                ITXEXRPT.dsSource.Merge(SetEnv);
                ITXEXRPT.DocType = app.company + "AB50GB12";
                ITXEXRPT.strExcelFile = app.company + @"\YGRABDOC.xls";
                string filename = ITXEXRPT.WriteExcelReport();
                SetDetail.Clear();
                vwABPOS.View.MoveCurrentTo(-1);
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }

        private void btnPrintBatches_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                //在这里，根据当前的混棉单号，查询对应的GAAUF和FP，可以利用ABAFUM，若不符合，不给打印。你的方法仅仅适合初次创建，此时用户或执行查询，你就失去了控制功能
                DataRow dwData = m_Data.GD.TBMain.NewRow();
                dwData["GAMANDANT"] = app.Mandant;
                dwData["GAAUFKRS"] = KRS;
                dwData["GAAUFLFD"] = LFD;
                dwData["GAAUFPOS"] = POS;
                dwData["GASA"] = "713";
                DataSet SResult = m_Data.GD.QGD29(dwData);
                DataTable tbGD = SResult.Tables[0].Copy();
                dwData = m_Data.VMU.TBMain.NewRow();
                dwData["ABAMANDANT"] = app.Mandant;
                dwData["ABAVKAUFKRS"] = KRS;
                dwData["ABAVKAUFLFD"] = LFD;
                dwData["ABAVKAUFPOS"] = POS;
                SResult = m_Data.VMU.QMU22(dwData);
                DataTable tbABA = SResult.Tables[0].Copy();
                if (tbGD.Rows.Count != tbABA.Rows.Count)
                {
                    MessageBox.Show("分盘结果异常,请联系管理人员");
                    return;
                }
                ITXEXRPT.dsSource = SetDetail;
                ITXEXRPT.dsSource.Merge(SetEnv);
                ITXEXRPT.dsSource.Merge(cTxt.TBTXT);
                ITXEXRPT.DocType = "YGRAB50GB20";
                string filename = ITXEXRPT.WriteExcelReport();
                SetDetail.Clear();
                vwABPOS.View.MoveCurrentTo(-1);
            }
            catch (Exception ex)
            { 
                Tracer.Error(ex.StackTrace, ex);
            }
        }


        private void txtAUFLFD_KeyUp(object sender, System.Windows.Input.KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                //btnQuery_Click(null, null);
            }
        }

        private void btnManualSetQty_Click(object sender, RoutedEventArgs e)
        {
            double batches = Convert.ToDouble(dwMU["ABAVKFARBE"].ToString());
            double ABARESMG = Convert.ToDouble(dwMU["ABARESMG"].ToString());
            double batchqty = Math.Round((ABARESMG / 10) / batches, 0) * 10;
            dwMU["ABAVKART"] = Helpers.Helper.Left(batchqty.ToString().PadRight(20), 20);//单盘重量
            INTEXDBC.UpdateABAUFM(dwMU, 3);
        }

        /* private void btnHelp_Click(object sender, RoutedEventArgs e)
         {
             if (ZoneHelp.Visibility == Visibility.Collapsed)
             {
                 ZoneHelp.Visibility = Visibility.Visible;
             }
             else
             {
                 if (ZoneHelp.Visibility == Visibility.Visible)
                 {
                     ZoneHelp.Visibility = Visibility.Collapsed;
                 }
             }
         }*/

        private void btnListMUReq_Click(object sender, RoutedEventArgs e)
        {
            DataSet SResult = m_Data.LoadMUReq(app.Mandant, txtKRSs.Text);
            SetEnv.GAAUF.Clear();
            SetEnv.Merge(SResult);
            cvYARNA.CustomFilter = null;
            cvMGAAUF.CustomFilter = null;
        }

        private void btnFilter_Click(object sender, RoutedEventArgs e)
        {
            string filter = "GAART LIKE '" + txtART.Text.ToString().Trim() + "%' AND  GAFARBE LIKE '" + txtFARBE.Text.ToString() + "'%";
            cvMGAAUF.CustomFilter = filter;
        }

        private void btnFilterClear_Click(object sender, RoutedEventArgs e)
        {
            cvMGAAUF.CustomFilter = null;
        }

        private void btnAddGAAUF_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (dwGAAUF == null)
                {
                    MessageBox.Show("请选择一条最相近的记录");
                    return;
                }
                DataRow dwData = SetDetail.Tables["GAAUF"].Rows.Add();
                dwData.ItemArray = dwGAAUF.ItemArray;
                var gapos = (from DataRow row in SetDetail.Tables["GAAUF"].AsEnumerable()
                             select row["GAPOS"].ToString())
                             .Max();
                int POS = Convert.ToInt16((string)gapos);
                dwData["GAPOS"] = Helpers.Helper.Right("00" + (POS + 1), 2);
                if (vwGAAUF.View != null)
                {
                    vwGAAUF.View.MoveCurrentToLast();
                }
                //MessageBox.Show("确定新原料添加之后，请手动点击制条需求");
                ResetTab();
                IsCalculate = true;
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }

        private void btnUpdateHMABPART_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (txtFlagABPART.Text.ToUpper() != "Y")
                {
                    MessageBox.Show("请手工将更新标志设置为Y");
                    return;
                }
                if (dwABPOS == null)
                {
                    MessageBox.Show("请选择粗纱单");
                    return;
                }
                if (dwABPOS["ABPPOSTYP"].ToString().Trim() != "HM")
                {
                    MessageBox.Show("请选择粗纱单,而不是其他单");
                    return;
                }
                string _KRS = dwABPOS["ABPAUFKRS"].ToString();
                string _LFD = dwABPOS["ABPAUFLFD"].ToString();
                string _POS = dwABPOS["ABPAUFPOS"].ToString();
                string _ART = Helpers.Helper.Left(dwABPOS["ABPART"].ToString().PadRight(20), 20);
                string _VAR = Helpers.Helper.Left(dwABPOS["ABPVAR"].ToString().PadRight(3), 3);
                string _FARBE = Helpers.Helper.Left(dwABPOS["ABPFARBE"].ToString().PadRight(10), 10);
                dwABPOS["ABPART"] = Helpers.Helper.Left(dwABPOS["ABPART"].ToString().PadRight(20), 20);
                dwABPOS["ABPVAR"] = Helpers.Helper.Left(dwABPOS["ABPVAR"].ToString().PadRight(3), 3);
                dwABPOS["ABPFARBE"] = Helpers.Helper.Left(dwABPOS["ABPFARBE"].ToString().PadRight(10), 10);
                INTEXDBC.UpdateABPOS(dwABPOS, 9);
                var qMU = from DataRow row in SetData.ABAUFM.AsEnumerable()
                          where row["ABAAUFKRS"].ToString() == _KRS
                          && row["ABAAUFLFD"].ToString() == _LFD
                          && row["ABAAUFPOS"].ToString() == _POS

                          select row;
                DataRow dwData = SetEnv.ICC_QUERYTB.NewRow();
                foreach (DataRow mu in qMU)
                {
                    string _VKAUFKRS = mu["ABAVKAUFKRS"].ToString();
                    string _VKAUFLFD = mu["ABAVKAUFLFD"].ToString();
                    string _VKAUFPOS = mu["ABAVKAUFPOS"].ToString();
                    string _UPOS = mu["ABAVKUPOS"].ToString();
                    if (_VKAUFLFD == "000000") continue;
                    dwData["GAMANDANT"] = mu["ABAMANDANT"];
                    dwData["GAAUFKRS"] = mu["ABAVKAUFKRS"];
                    dwData["GAAUFLFD"] = mu["ABAVKAUFLFD"];
                    dwData["GAAUFPOS"] = mu["ABAVKAUFPOS"];
                    dwData["GASA"] = "713";
                    dwData["GAPOS"] = mu["ABAVKUPOS"];
                    dwData["GAART"] = _ART;
                    dwData["GAVAR"] = _VAR;
                    dwData["GAFARBE"] = _FARBE;
                    INTEXDBC.UpdateGAAUF(dwData, 16);
                }
                dwData = SetData.ICC_ABAX.NewRow();
                dwData["ABAAUFKRS"] = _KRS;
                dwData["ABAAUFLFD"] = _LFD;
                dwData["ABAAUFPOS"] = _POS;
                dwData["ABAART"] = _ART;
                dwData["ABAVAR"] = _VAR;
                dwData["ABAFARBE"] = _FARBE;
                INTEXDBC.UpdateICC_ABAX(dwData, 2);
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }

        }

        private void btnRepaire_Click(object sender, RoutedEventArgs e)
        {
            if (dwABPOS == null)
            {
                MessageBox.Show("请选择需要回修的生产单");
                return;
            }
            var GAAUFPOS = (from DataRow row in SetDetail.Tables["GAAUF"].AsEnumerable()
                            select row["GAAUFPOS"].ToString())
                         .Max();
            int HXPOS = Convert.ToInt16((string)GAAUFPOS);
            if (HXPOS > 500)
            {
                MessageBox.Show("请选择原始单进行回修");
                return;
            }
            MUREQ.Focus();
            if (!IsRepair)
            {
                IsCanChgGAAUF = true;
                IsRepair = true;
            }
            if (vwGAAUF.View != null)
            {
                vwGAAUF.View.MoveCurrentToLast();
            }
            if (dwGAAUF == null)
                return;
            txtRepaire.Foreground = Brushes.Red;
            btnRepQty.Foreground = Brushes.Red;
            btnInitializedMU.IsEnabled = true;
            DataRow dwData = SetDetail.Tables["GAAUF"].Rows.Add();
            dwData.ItemArray = dwGAAUF.ItemArray;
            var gapos = (from DataRow row in SetDetail.Tables["GAAUF"].AsEnumerable()
                         select row["GAPOS"].ToString())
                         .Max();
            int POS = Convert.ToInt16((string)gapos);

            dwData["GAPOS"] = Helpers.Helper.Right("00" + (POS + 1), 2);
            dwData["GAART"] = dwABPOS["ABPART"];
            dwData["GAVAR"] = dwABPOS["ABPVAR"];
            dwData["GAFARBE"] = dwABPOS["ABPFARBE"];
            dwData["GAKG1"] = 0;
            dwData["GAKG2"] = 0;
            dwData["GAKG3"] = 0;
            dwData["GAKG4"] = 0;
            dwData["GAKG5"] = 0;
            dwData["GAKG6"] = 0;
            dwData["GAKG7"] = 0;
            dwData["GABEM"] = Helpers.Helper.Left("*HX*".PadRight(40), 40);
            SetDetail.Tables["GAAUF"].AcceptChanges();
            if (vwGAAUF.View != null)
            {
                vwGAAUF.View.MoveCurrentToLast();
            }
            MessageBox.Show("请先调整准确的回修单重量。", "保证原有原料总量不变");
        }

        private void TextBox_TextChanged(object sender, System.Windows.Controls.TextChangedEventArgs e)
        {
            //ResetTab();
            if (!IsINBookingmode)
            {
                IsCalculate = true;
            }
            if (IsSave)
            {
                IsCalculate = false;
            }
        }


    }
}
